package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author 黑马程序员
 * @since 2022-06-06
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(HttpServletRequest req, @RequestBody Category category) {

        //打印日志
        log.info("添加员工的信息：{}", category.toString());
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> pageSelect(int page, int pageSize) {
        log.info("page = {},pageSize = {}", page, pageSize);
        //构造分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper();
        //添加排序条件
        qw.orderByAsc(Category::getType).orderByAsc(Category::getSort);
        //调用方法
        categoryService.page(pageInfo,qw);
        return R.success(pageInfo);
    }
    @PutMapping
    public R<String> statusById(HttpServletRequest req, @RequestBody Category category) {
        log.info(category.toString());
        //修改需要更新修改人，通过你登陆的id在session中的id获取
//        Long empid = (Long) req.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(empid);
        categoryService.updateById(category);
        String msg ="修改分类信息成功";
        return R.success(msg);
    }

    @DeleteMapping
    public R<String> deleteById(Long id){
        log.info("删除分类id为：{}",id);
        categoryService.deleteById(id);
        return R.success("删除成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> categoryByType(Category category){
        //构造条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper();
        //添加条件 先进行判断是否为空
        qw.eq(category.getType()!=null,Category::getType,category.getType());
        //添加排序条件
        qw.orderByAsc(Category::getType).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(qw);
        return R.success(list);
    }


}

